using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class SettingsLoadingScript : MonoBehaviour
{
    public DiceSettings Settings;
    private void Awake()
    {
        var path = Path.GetFullPath("settings.json", Application.streamingAssetsPath);
        var readMePath = Path.GetFullPath("settings-readme.txt", Application.streamingAssetsPath);
        const string key = "I know what I am doing. Please load `settings.json` at the next run.";

        var file = new FileInfo(path);
        var readMeFile = new FileInfo(readMePath);
        try
        {
            if (File.ReadAllText(readMePath).Trim() == key)
            {
                var content = File.ReadAllText(path);
                JsonUtility.FromJsonOverwrite(content, Settings);
            }
        }
        catch(Exception e)
        {
            Debug.LogException(e);
            // do nothing
        }

        try
        {
            var content = JsonUtility.ToJson(Settings, true);
            using var stream = file.CreateText();
            stream.Write(content);

            using var readMeStream = readMeFile.CreateText();
            readMeStream.WriteLine("You can modify the settings by editing `settings.json`.");
            readMeStream.WriteLine();
            readMeStream.WriteLine("After you modified it and want the new settings to be loaded,");
            readMeStream.WriteLine("you should delete all the lines in this file EXCEPT the last one.");
            readMeStream.WriteLine();
            readMeStream.WriteLine("If you forgetted to do this,");
            readMeStream.WriteLine("the settings will be changed back at the next run.");
            readMeStream.WriteLine();
            readMeStream.WriteLine("So as a backup,");
            readMeStream.WriteLine("you may copy the settings elsewhere before editting it.");
            readMeStream.WriteLine();
            readMeStream.WriteLine("For developers of the program only:");
            readMeStream.WriteLine("DO NOT EDIT THIS FILE in unity!");
            readMeStream.WriteLine("Your change could affect the default settings!");
            readMeStream.WriteLine("If you do want to modify it,");
            readMeStream.WriteLine("you can edit `Assets/Settings.asset` directly.");
            readMeStream.WriteLine();
            readMeStream.WriteLine(key);
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            // do nothing
        }
    }
}
